﻿Imports System.Net
Imports System.Text
Imports System.IO
Imports System.Threading.Tasks
Imports System.Windows.Threading

Public Class DHLOnlineLogin
    Implements IManager

    Private _login As HttpWebRequest
    Private _isloggedin As Boolean = False
    Private _isloggingIn As Boolean = False
    Private _dispatcher As Dispatcher
    Private _cookiecontainer As CookieContainer

    Public Sub New(dispatcher As Dispatcher)
        _dispatcher = dispatcher
        LogIn()
    End Sub

    Public Property Username As String
        Get
            Return ""
        End Get
        Set(value As String)

        End Set
    End Property

    Public Property Password As String
        Get
            Return ""
        End Get
        Set(value As String)

        End Set
    End Property

    Public ReadOnly Property IsLoggedIn As Boolean
        Get
            Return _isloggedin
        End Get
    End Property

    Public ReadOnly Property IsLoggingIn As Boolean
        Get
            Return _isloggingIn
        End Get
    End Property

    Public Sub LogIn()
        _cookiecontainer = New CookieContainer
        Try
            _isloggingIn = True
            Dim response As HttpWebResponse = CreateWebRequest("https://nolb.dhl.de/nextt-online-business/jsp/login.do", "").GetResponse()
            SetCookie(response.Headers("Set-Cookie"))
            _cookiecontainer.Add(New Uri("http://nolb.dhl.de"), New Cookie("customer", Username))

            response = CreateWebRequest("https://nolb.dhl.de/nextt-online-business/jsp/login.do", "login=" + Username + "&password=" + Password + "&doLogin=Anmelden").GetResponse()
            If response.StatusCode = 302 Then
                Console.WriteLine("Login successfull")
                SetCookie(response.Headers("Set-Cookie"))
                _isloggedin = True
            ElseIf response.StatusCode = HttpStatusCode.OK Then
                Console.WriteLine("Login failed")
                _isloggedin = False
            End If
            _isloggingIn = False
        Catch ex As Exception
            ' No connection...
        End Try
    End Sub

    Public Function GetDetails(id As String) As Boolean Implements IManager.GetDetails
        If IsLoggedIn Then
            Task.Factory.StartNew(Sub()
                                      Dim response As HttpWebResponse = CreateWebRequest("https://nolb.dhl.de/nextt-online-business/jsp/nol/piece/pieceSearchCheckAction.do", "timeIntervall:12&shipmentCode:" + id + "&pieceCustomerReference:&tasOrderNo:&search_ta:Start").GetResponse()
                                      Dim s As Stream = response.GetResponseStream
                                      Dim sr As New StreamReader(s)
                                      Dim html = sr.ReadToEnd()
                                      _dispatcher.BeginInvoke(Sub()
                                                                  RaiseEvent GetDetailsCompleted(id, html)
                                                              End Sub)
                                  End Sub)
            Return True
        ElseIf IsLoggingIn Then

        End If
        Return False
    End Function

    Private Sub SetCookie(c As Cookie)
        _cookiecontainer.SetCookies(New Uri("http://nolb.dhl.de"), c.Name + "=" + c.Value)
    End Sub

    Private Sub SetCookie(s As String)
        s = s.Replace("JSESSIONID=", "")
        Dim jsid = Mid(s, 1, s.IndexOf(";"))
        _cookiecontainer.SetCookies(New Uri("http://nolb.dhl.de"), "JSESSIONID=" + jsid)
    End Sub

    Private Function GetCookieHeader() As String
        Return _cookiecontainer.GetCookieHeader(New Uri("http://nolb.dhl.de"))
    End Function

    Private Function CreateWebRequest(url As String, content As String) As HttpWebRequest
        Dim req As HttpWebRequest = HttpWebRequest.Create(url)
        req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11"
        req.Method = "POST"
        req.Host = "nolb.dhl.de"
        'req.Headers.Add("Cookies", GetCookieHeader)
        req.CookieContainer = _cookiecontainer
        req.Headers.Add("Cache-Control", "max-age=0")
        req.Headers.Add("Origin", "https://nolb.dhl.de")
        req.ContentType = "application/x-www-form-urlencoded"
        req.AllowAutoRedirect = False
        If Not String.IsNullOrEmpty(content) Then
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(content)
            req.ContentLength = byteArray.Length
            req.GetRequestStream().Write(byteArray, 0, byteArray.Length)
        End If
        Return req
    End Function

    Public Function CreateNewPackage(id As String) As IPackager Implements IManager.CreateNewPackage
        Return New DHLBusiness(Me, id)
    End Function

    Public Event LogInFailed()
    Public Event LogInSuccessfull()
    Public Event GetDetailsCompleted(id As String, html As String) Implements IManager.GetDetailsCompleted
End Class
